package leetCode.offer55_ii;

import java.util.Stack;

public class Solution2 implements Solution{

    @Override
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            int[] max = new int[1];
            if(root.left!=null){
                stack.add(root.left);
                getDeep(root.left,0,max);
            }
            int leftDeep = max[0];
            max[0] = 0;
            if(root.right!=null){
                stack.add(root.right);
                getDeep(root.right,0,max);
            }
            int rightDeep = max[0];
            if(leftDeep-rightDeep>1||rightDeep-leftDeep>1){
                return false;
            }
        }
        return true;
    }

    public void getDeep(TreeNode root,int deep,int[] max){
        if(root!=null){
            deep = deep + 1;
            getDeep(root.left,deep,max);
            getDeep(root.right,deep,max);
            if(deep>max[0]) max[0] = deep;
        }
    }

}
